package com.hy.dubboprovider.Service;

import com.hy.common.Service.UserService;
import com.hy.common.pojo.User;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.config.annotation.DubboService;

import java.io.Serializable;

/**
 * @author: 王富贵
 * @description:
 * @createTime: 2022年10月04日 19:58:18
 */
@DubboService
public class UserServiceImpl implements UserService {
    @Override
    public User getUser(Integer id) {
        return new User(id, "坏银");
    }

    @Override
    public String SayHello() {
        return "hello world";
    }

    // server-stream 服务端流.多次响应客户端消息
    @Override
    public void sayHelloServerStream(String name, StreamObserver<String> response) {
        // 循环响应信息，建立长连接，而不是调用一次
        for (int i = 0; i < 10; i++) {
            response.onNext("hello," + name);
        }

        // 响应完成,结束方法
        response.onCompleted();
    }

    @Override
    public StreamObserver<String> sayHelloStream(StreamObserver<String> response) {
        return new StreamObserver<String>() {

            //想要流接收消息方法
            @Override
            public void onNext(String data) {
                System.out.println(data);
                response.onNext("hello,"+data);
            }

            // 响应流错误执行方法
            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            // 响应流完成方法
            @Override
            public void onCompleted() {
                System.out.println("onCompleted");
                response.onCompleted();
            }
        };
    }
}
